<template>
    <div style="background:#f9f9f9">
	<van-form ref="attrFrom" @submit="onSubmit">
       <van-field
	   name="my-field" 
	   :label="attr.attrName"
	   label-align="right"
	   label-width="8em"
	   :right-icon="'edit'"
	   >
		<template #input>
		  <smart-input id="service" @sync="syncService" :props="attr"></smart-input>
		</template>
	  </van-field>
	  </van-form>
    </div>
</template>

<script>
  import smartInput from './smart-input'

  export default {
    data () {
      return {
        loadingMap: {},
        showPicker: {}, // 控制picker开关
        showSubmit: false, // 显示提交按钮
        appUrl: '',
        loadingData: {appUrl: true},
        value1: true,
        index: 1,
        page: 1,
        orders: [],
        custAttr: [],
        orderAttr: [],
        custCount: 10,
        isFlod1: true,
        isOther: false,
        loading: false,
        pageNo: 1,
        pageSize: 3,
        orderBy: '',
        dataList: [],
        count: false,
        noCount: false,
        complain: [],
        popupVisible: false,
        popupVisible1: false,
        popupVisible2: false,
        popupVisible3: false,
        dialogTableVisible2: false,
        item: {},
        visible: true,
        searchForm: {
          callingPhone: '',
          calledPhone: '',
          dcalledPhone: '',
          dcalledPhone1: '',
          rhphoneAccNum: '',
          success: '',
          success1: ''
        },
        staffInfo: {},
        myVar: 0,
        cishu: 0,
        callId: '',
        remark: '',
        custOrderNbr: '',
        fallbackObj: {
          feedbackDesc: ''
        },
        useRate: '',
        balance: '',
        slots: [{
          flex: 1,
          values: [],
          className: 'slot1',
          defaultIndex: 0
        }],
        classs: ['blue', 'orage', 'green'],
        operAttrStruct: {
          staffId: '',
          operOrgId: '',
          // operTime: '',
          operServiceId: ''
          // lanId: '22'
        },
        formConfig: {},
        form: {},
        isFans: ''
      }
    },
    components: {
      gjDetail,
      DragElement,
      AttrForm
    },
    computed: {
      ...mapState('sct/oapOrder', ['oapOrder']),
      ...mapState('so/cust', ['linkPhone', 'lanName', 'prodId', 'certAddress']),
      ...mapState('sct/cust', ['accProdsStr']),
      ...mapState('so/common', ['accNum', 'regionId', 'sysSource', 'channelId']),
      ...mapState('sct/common', ['stationId', 'staffCode', 'staffAccNum', 'extStaffCode', 'orgId', 'channels']),
      attrName (fic) {
        return fic.valueMap[fic.itemValue]
      }
    },
    created () {
      this.setAppParams()
      this.queryFormConfig('oapOrder')
      this.operAttrStruct.staffId = this.extStaffCode
      this.operAttrStruct.operOrgId = this.orgId
      this.fetchUserInfo()
      this.queryOrderAttr()
      this.qryAttrValue('20210810027')
      this.qryIsFans()
    },
    mounted () {
      let fromPage = this.$route.query.fromPage
      if (fromPage && fromPage === 'custOrders') {
        console.log('来自微信列表页面')
      } else {
        if (window.history && window.history.pushState) {
          history.pushState(null, null, document.URL)
          window.addEventListener('popstate', this.goBack, false)
        }
      }
    },
    destroyed () {
      window.removeEventListener('popstate', this.goBack, false)
    },
    methods: {
      qryIsFans () {
        if (this.sysSource === '101501') {
          let params = {
            accNum: this.oapOrder.linkPhone,
            staffCode: this.staffCode
          }
          this.$http({
            url: '/oaporderinfo/sctOapOrderInfo/qryIsFans',
            method: 'post',
            data: params,
            headers: {
              'Content-Type': 'application/json; charset=utf-8'
            }
          }).then(({data}) => {
            if (data.resultCode === '0') {
              this.isFans = data.resultObject.isFans
            }
          })
        }
      },
      map2List (map) {
        let list = []
        for (let key in map) {
          list.push({'value': key, 'label': map[key]})
        }
        return list
      },
      formatDateTime (time) {
        //   格式：yyyy-MM-dd hh:mm:ss
        let date = new Date(Number(time))
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' '
        let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':'
        let m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':'
        let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        return Y + M + D + h + m + s
      },
      clickField (fic) {
        if (fic.isEditable === '0') {
          return
        }
        this.$set(this.showPicker, fic.itemKey, true)
      },
      onPickerConfirm (time) {
        this.form.createDate = this.formatDateTime(time)
        this.showPicker.createDate = false
      },
      onSubmit () {
        this.loadingMap['submit'] = true
        this.$http({
          url: '/oaporderinfo/sctOapOrderInfo/save',
          method: 'post',
          data: this.form
        }).then(({data}) => {
          this.loadingMap['submit'] = false
          if (data && data.success) {
            this.$message.success('保存成功！')
          }
        })
      },
      enableField (fic) {
        this.focus()
        this.$set(fic, 'editable', true)
//        fic.editable = true
      },
      setAppParams () {
        let token = Vue.cookie.get('token')
//        let ssoNo = token.substring(0, 30)
//        let params = {'ssoNo': ssoNo, 'sysCode': 'sysCode', 'token': token}
//        let key = '2019@YXS&app）'
//        let data = getAES(params, key)
        this.loadingData['appUrl'] = true
        this.$http({
          url: '/workOrder/sendOrder/getAppDataParam',
          method: 'post',
          data: {staffCode: this.staffCode, channelId: this.channelId, token: token},
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        }).then(({data}) => {
          this.loadingData['appUrl'] = false
          if (data) {
            this.appUrl = 'chinatelecomyxs://?data=' + data
          }
        })
      },
      qryAttrValue (attrId) {
        this.$http({
          url: '/order/soAttrValue/qryOapAttrValue',
          method: 'post',
          data: {
            'attrId': attrId
          }
        }).then(({data}) => {
          if (data && data.success) {
            let values = []
            let attrs = data.resultObject.oapAttrValue
            for (let i in attrs) {
              let item = {index: i, code: attrs[i].attrValue, name: attrs[i].attrValueName}
              values.push(item)
            }
            this.slots[0].values = values
          }
        })
      },
      chooseAccNum (num) {
        if (num === '1') {
          if (this.searchForm.success === 'success') {
            this.searchForm.success = ''
            this.searchForm.calledPhone = ''
          } else {
            this.searchForm.calledPhone = this.linkPhone
            this.searchForm.success = 'success'
            this.searchForm.success1 = ''
          }
        } else {
          if (this.searchForm.success1 === 'success') {
            this.searchForm.success1 = ''
            this.searchForm.calledPhone = ''
          } else {
            this.searchForm.calledPhone = this.searchForm.rhphoneAccNum
            this.searchForm.success1 = 'success'
            this.searchForm.success = ''
          }
        }
      },
      showDetail (item) {
        this.dialogTableVisible2 = true
        this.item = item
      },
      goBack () {
        console.log('进入自定义返回')
        this.$router.replace({path: '/oap-order', query: {back: 'back'}})
      },
      desensitize (value) {
        let length = value ? value.length : 0
        let desLen = Math.ceil(length / 3)
        let result = []
        for (let i = length - 1; i >= 0; i--) {
          if (i < length - desLen && i >= length - 2 * desLen) {
            result.push('*')
          } else {
            result.push(String(value[i]))
          }
        }
        return result.reverse().join('')
      },
      queryFormConfig (formCode) {
        this.$http({
          url: '/formconfig/sctFormConfig/queryByWhere',
          method: 'post',
          data: {
//            formCode: formCode,
            orderSource: this.oapOrder.orderSource
          },
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        }).then(({data}) => {
          if (data.success) {
            this.formConfig = data.sctFormConfig // 融合手机号
            for (let element of this.formConfig.sctFormItemConfigs) {
              element.itemValue = this.oapOrder[element.itemKey]
              if (this.oapOrder.statusCd !== '10') {
                element.isEditable = '0'
              }
              this.$set(this.form, element.itemKey, element.itemValue)
            }
          }
        })
      },
      async fetchUserInfo () {
        var params = {}
        params['accNum'] = this.accNum
        if (this.regionId) {
          params['regionId'] = this.regionId
        }
        let res = await this.$http({
          url: '/order/soCommonQuery/qryAccProdInstList',
          method: 'post',
          data: params,
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        })
        var data = res.data
        if (data.resultCode === '0') {
          this.$store.commit('so/cust/updateCust1', data.resultObject)
        }
        params['prodId'] = this.prodId
        this.$http({
          url: '/common-user/queryOfferMember',
          method: 'post',
          data: params,
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        }).then(({data}) => {
          if (data.resultCode === '0') {
            this.$store.commit('sct/cust/updateCust', data.resultObject)
            this.searchForm.rhphoneAccNum = data.resultObject.linkPhone // 融合手机号
          }
        })
        this.operAttrStruct.operServiceId = 'AccuUseQry'
        this.$http({
          url: '/common-user/accuUseQry',
          method: 'post',
          data: {
            accNbr: this.accNum,
            prodId: this.prodId,
            ...this.operAttrStruct
          },
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        }).then(({data}) => {
          if (data.resultCode === '0') {
            this.useRate = data.resultObject.useRate
            this.balance = data.resultObject.balance
          }
        })
      },
      queryOrderAttr () {
        let self = this
        let queryData = {}
        queryData.orderId = self.oapOrder.orderId
        self.$http({
          url: '/oaporderinfoattr/sctOapOrderInfoAttr/list',
          method: 'post',
          data: queryData
        }).then(({data}) => {
          if (data && data.success) {
            self.orderAttr = data.page.list
            self.getCount(self.orderAttr)
          } else {
            self.$alert(data.msg, '错误信息', {
              confirmButtonText: '确定'
            })
          }
        })
      },
      getCount (list) {
        this.custCount = 10
        if (this.custCount > list.length) {
          this.custCount = list.length
        }
      },
      ocFlod (isFlod) {
        this.isFlod1 = isFlod
        if (isFlod) {
          this.getCount(this.orderAttr)
          this.$refs.btn1.$el.innerText = '展开全部内容'
        } else {
          this.custCount = this.orderAttr.length
          this.$refs.btn1.$el.innerText = '折叠'
        }
      },
      closetc () {
        this.$router.go(-1)
      },
      onValuesChange (picker, values) {
        let value = values[0]
        if (value) {
          this.fallbackObj.feedbackResult = value.code
          this.fallbackObj.feedbackDesc = value.name
          if (value.code === '8000') {
            this.isOther = true
            this.fallbackObj.feedbackDesc = ''
          } else {
            this.isOther = false
          }
        }
      },
      tijiao (type) {
        if (this.custOrderNbr === '') {
          this.$message.error('请输入订单流水！')
          return false
        }
        let feedbackResult = '7000'
        let feedbackDesc = '成功'
        let statusCd = '70'
        let self = this
        this.$messagebox({
          title: '提示',
          message: '确定要闭单吗？',
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          if (action === 'confirm') {
            this.popupVisible3 = false
            self.fallbackObj.feedbackResult = feedbackResult
            self.fallbackObj.feedbackDesc = feedbackDesc
            self.fallbackObj.statusCd = statusCd
            self.tijiaoht()
          }
        })
      },
      writeOutCallLog () {
        if (this.callId === '') {
          this.$message('还没有进行外呼！')
          return false
        }
        this.popupVisible2 = true
      },
      huidan () {
        this.popupVisible3 = true
      },
      tijiaoht () {
        this.fallbackObj = Object.assign(this.oapOrder, this.fallbackObj)
        this.fallbackObj.custOrderNbr = this.custOrderNbr
        this.$http({
          url: '/oaporderinfo/sctOapOrderInfo/tijiao',
          method: 'post',
          data: this.fallbackObj,
          loading: true
        }).then(({data}) => {
          if (data && data.success) {
            this.$message.success(data.msg)
            this.$router.replace({path: '/oap-order', query: {back: 'back'}})
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      selectStatus () {
        this.fallbackObj.statusCd = '80'
        this.popupVisible1 = false
        this.tijiaoht()
      },
      cancelSelectStatus () {
        this.popupVisible1 = false
      },
      other () {
        this.popupVisible1 = true
      },
      baseClick (flag) {
        window.location.href = 'ftnn:login'
      },
      zbaseClick (row) {
        let queryData = {
          'orderId': row.orderId,
          'preStatusCd': '00',
          'staffId': this.stationId,
          'statusCd': '10',
          'actionType': 'A'
        }
        this.$http({
          url: '/oaporderinfo/sctOapOrderInfo/updateStatus',
          method: 'post',
          data: queryData
        }).then(({data}) => {
          if (data && data.success) {
            this.$set(row, 'disabled', true)
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      moreBusi () {
        this.index = 4
        this.busiList()
      },
      busiList (more) {
        this.loading = true
        let custId = this.oapOrder.custId
        let linkPhone = this.oapOrder.linkPhone
        let certNum = this.oapOrder.certNum
        if (more !== 'more') {
          this.pageNo = 1
        }
        this.$http({
          url: '/oaporderinfo/sctOapOrderInfo/list',
          method: 'post',
          params: {
            'pageNo': this.pageNo,
            'pageSize': this.pageSize,
            'orderBy': this.orderBy,
            'channels': this.channels,
            'linkPhone': linkPhone,
            'certNum': certNum,
            'custId': custId,
            'flag': '1',
            'excludeOrderId': this.oapOrder.orderId,
            'statusCds': '00'
          }
        }).then(({data}) => {
          if (data && data.success) {
            let result = data.page.list
            let pageCount = data.page.count
            if (result && result.length > 0) {
              this.count = true
              this.noCount = false
            }
            if (more === 'more') {
              result.forEach((el, index) => {
                this.dataList.push(el)
              })
            } else {
              this.dataList = result
            }
            if (pageCount === this.dataList.length) {
              this.noCount = true
              this.count = false
            }
          }
          this.loading = false
        })
      },
      loadMore () {
        this.pageNo = this.pageNo + 1
        this.busiList('more')
      },
      complaints () {
        this.index = 3
        let params = {
          accNum: this.oapOrder.linkPhone,
          regionId: this.oapOrder.acceptLanId
        }
        this.$http({
          url: '/contactorder/sctContactOrder/qryTS',
          method: 'post',
          data: params,
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        }).then(({data}) => {
          if (data && data.success) {
            let result = data.list
            result.forEach((resulti) => {
              let temp = {
                content: resulti.COM_CONTENT,
                timestamp: resulti.CREATE_DATE,
                size: 'large',
                type: 'primary'
              }
              this.complain.push(temp)
            })
          }
        })
      },
      marketing () {
        this.index = 2
        let params = {
          latnId: this.oapOrder.acceptLanId,
          objectType: '1',
          objectId: this.oapOrder.custId,
          orderType: 'oapOrder'
        }
        this.$http({
          url: '/contactorder/sctContactOrder/qryMarketing',
          method: 'post',
          params: params
        }).then(({data}) => {
          if (data && data.success) {
            this.orders = data.dataList
          }
        })
      },
      callOut () {
        this.popupVisible = true
        this.visible = false
        this.searchForm.callingPhone = this.staffAccNum
        this.searchForm.calledPhone = this.oapOrder.linkPhone
        this.searchForm.dcalledPhone = this.desensitize(this.oapOrder.linkPhone)
      },
      callWx () {
        wx.config({
          beta: true,
          debug: false,
          appId: 'ajs.corpId',
          timestamp: 'js.timestamp',
          nonceStr: 'js.nonceStr',
          signature: 'js.signature',
          jsApiList: ['openEnterpriseChat']
        })
        wx.ready(function () {
          this.openCustLink()
        })
      },
      openCustLink () {
        wx.openEnterpriseChat({
          userIds: '',
          externalUserIds: 'externalUserId',
          groupName: '',
          success: function (res) {
          },
          fail: function (res) {
            if (res.errMsg.indexOf('function not exist') > -1) {
              alert('版本过低请升级')
            }
          }
        })
      },
      closePopup () {
        this.popupVisible = false
        this.visible = true
      },
      myTimer () {
        let params = {
          callId: this.callId,
          callNum: this.staffAccNum,
          beCalledNum: this.workOrder.mobilePhone,
          billId: this.workOrder.contactOrderId,
          callStaffId: this.stationId
        }
        this.$http({
          url: '/call/outCallResult',
          method: 'post',
          data: params
        }).then(({data}) => {
        })
      },
      save () {
        let params = {
          callId: this.callId,
          remark: this.remark,
          billId: this.oapOrder.orderId,
          callStaffId: this.staffCode
        }
        this.$http({
          url: '/call/update',
          method: 'post',
          data: params
        }).then(({data}) => {
          if (data && data.success) {
            this.popupVisible2 = false
            this.$message.success('保存成功！')
          }
        })
      },
      confirm () {
        if (this.searchForm.calledPhone === '') {
          this.$messagebox('错误', '被叫号码为空！')
          return false
        }
        this.popupVisible = false
        let params = [{
          srcOrderNbr: this.workOrder.contactOrderId,
          staffId: this.staffInfo.staffCode,
          callingPhone: this.searchForm.callingPhone,
          calledPhone: this.searchForm.calledPhone,
          operSrc: '强触点系统'
        }]
        this.$http({
          url: '/call/outCall',
          method: 'post',
          data: params,
          loading: true,
          loadingText: '外呼中...',
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        }).then(({data}) => {
          let res = data.res
          if (res && res.resultObject.resultCode === '0') {
            this.callId = res.resultObject.callId
            this.myTimer()
            this.visible = true
            // this.myVar = setInterval(this.myTimer, 3000)
          } else {
            this.visible = true
          }
        })
      }
    }
  }
</script>

<style>
    .disableTel-box {
        width: 5rem;
        height: 5rem;
        padding: 1.25rem;
        border-radius: 50%;
        background: linear-gradient(#c6ccd0, #9aa9be);
        position: absolute;
        top: 19rem;
        right: 1.625rem;
    }

    .mint-popup {
        left: 50% !important;
        right: -30% !important;
    }

    .btn-right {
        float: right;
        padding-right: 1.9rem;
        margin-bottom: 1rem;
    }
    .aa {
      width:90%;
      overflow: hidden; 
      border-radius:5px; 
      margin: auto; 
      margin-top:0.9375rem; 
      background: #fff;
      padding:0 5%; 
      margin-bottom:0.9375rem;
    }
    .bb {
      color: #67C23A;
    }
    .cc {
      color:#F56C6C;
    }
</style>
